/**   
* @Title: PoetryThread.java
* @Package org.xaoyaoyao.spider.thread
* @Description: TODO
* @author xaoyaoyao
* @date Jan 25, 2019 5:44:10 PM
* @version V1.0   
*/
package org.xaoyaoyao.spider.thread;

import org.apache.commons.lang3.StringUtils;
import org.xaoyaoyao.spider.entity.SpiderTask;
import org.xaoyaoyao.spider.processor.Processor;
import org.xaoyaoyao.spider.redis.RedisService;
import org.xaoyaoyao.spider.util.Constants;
import org.xaoyaoyao.spider.util.StopSignalReceiver;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: PoetryThread
 * @Description: TODO
 * @author xaoyaoyao
 * @date Jan 25, 2019 5:44:10 PM
 * 
 */
@Slf4j
public class PoetryThread implements Runnable {

	private RedisService redisService;

	private Processor processor;

	public PoetryThread(RedisService redisService, Processor processor) {
		super();
		this.redisService = redisService;
		this.processor = processor;
	}

	@Override
	public void run() {
		log.error(">>>>>>>> 开始执行任务...");
		while (!isExit()) {
			try {
				SpiderTask task = getGrabTask();
				processor.handle(task);
			} catch (Exception e) {
				log.error(">>>>>>>> Check Thread Exception!", e);
			}
		}
		if (isExit()) {
			log.error(">>>>>>>> 关闭任务！！！");
		}
	}

	private SpiderTask getGrabTask() {
		try {
			// 获取任务，可从redis获取任务
			String json = redisService.rpop(Constants.SPIDER_TASK_PROCESSED);
			log.debug(">>>>>>>> SpiderTask >> {}", json);
			if (StringUtils.isNotBlank(json)) {
				return SpiderTask.parse(json);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}

	private boolean isExit() {
		return StopSignalReceiver.isReceived();
	}
}
